// mock-api.js - 用于本地测试的模拟API服务器
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 3000;

// 中间件
app.use(cors());
app.use(express.json());

// 模拟管理员数据
const adminCredentials = {
  username: 'jxhjschool',
  password: 'jxhjschool_2038'
};

// 模拟数据库
const submissions = [
  {
    id: 1,
    grade: 7,
    class: 2,
    name: '张同学',
    title: '校园生活随笔',
    category: 1,
    content: '这是一篇关于校园生活的随笔...',
    status: 0,
    submitted_at: new Date().toISOString()
  },
  {
    id: 2,
    grade: 8,
    class: 3,
    name: '李同学',
    title: '运动会感想',
    category: 2,
    content: '运动会真的很精彩...',
    status: 1,
    submitted_at: new Date().toISOString()
  }
];

// 生成会话token
function generateToken(adminId, username) {
  return Buffer.from(`${adminId}|${username}|${Date.now()}`).toString('base64');
}

// 验证token
function verifyToken(token) {
  try {
    const decoded = Buffer.from(token, 'base64').toString('ascii');
    const [adminId, username, timestamp] = decoded.split('|');
    
    // 检查token是否过期（1小时）
    const now = Date.now();
    if (now - parseInt(timestamp) > 3600000) {
      return null;
    }
    
    return { id: parseInt(adminId), username };
  } catch (e) {
    return null;
  }
}

// API端点

// 管理员登录
app.post('/api/admin/login', (req, res) => {
  const { username, password } = req.body;
  
  if (username === adminCredentials.username && password === adminCredentials.password) {
    const token = generateToken(1, username);
    
    res.json({
      success: true,
      message: '登录成功',
      token: token,
      admin: {
        id: 1,
        username: username
      }
    });
  } else {
    res.status(401).json({
      error: '用户名或密码错误'
    });
  }
});

// 管理员验证
app.get('/api/admin/verify', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ error: '未授权' });
  }
  
  const adminInfo = verifyToken(token);
  
  if (adminInfo) {
    res.json({
      success: true,
      admin: adminInfo
    });
  } else {
    res.status(401).json({ error: '无效的token' });
  }
});

// 管理员登出
app.post('/api/admin/logout', (req, res) => {
  res.json({
    success: true,
    message: '登出成功'
  });
});

// 获取统计数据
app.get('/api/admin/stats', (req, res) => {
  const total = submissions.length;
  const pending = submissions.filter(s => s.status === 0).length;
  const approved = submissions.filter(s => s.status === 1).length;
  const rejected = submissions.filter(s => s.status === 2).length;
  
  res.json({
    success: true,
    stats: {
      total,
      pending,
      approved,
      rejected
    }
  });
});

// 获取投稿列表
app.get('/api/submissions', (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 20;
  const status = req.query.status ? parseInt(req.query.status) : null;
  
  let filtered = submissions;
  if (status !== null) {
    filtered = submissions.filter(s => s.status === status);
  }
  
  const start = (page - 1) * limit;
  const end = start + limit;
  const paginated = filtered.slice(start, end);
  
  res.json({
    success: true,
    data: paginated,
    pagination: {
      page,
      limit,
      total: filtered.length,
      pages: Math.ceil(filtered.length / limit)
    }
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Mock API服务器运行在 http://localhost:${PORT}`);
  console.log('可用API端点:');
  console.log('- POST /api/admin/login - 管理员登录');
  console.log('- GET /api/admin/verify - 验证管理员会话');
  console.log('- POST /api/admin/logout - 管理员登出');
  console.log('- GET /api/admin/stats - 获取统计数据');
  console.log('- GET /api/submissions - 获取投稿列表');
});